package ar.edu.unq.tpi.uis.tepe3.wicket.pages;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.list.PropertyListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.hibernate.Session;
import org.hibernate.Transaction;

import ar.edu.unq.tpi.uis.tepe3.dominio.Group;
import ar.edu.unq.tpi.uis.tepe3.dominio.User;
import ar.edu.unq.tpi.uis.tepe3.persistencia.HibernateUtil;
import ar.edu.unq.tpi.uis.tepe3.wicket.components.GroupListView;
import ar.edu.unq.tpi.uis.tepe3.wicket.components.UserToGroupForm;
import ar.edu.unq.tpi.uis.tepe3.wicket.model.GroupList;

public class UserToGroupPage extends LayoutPage {
	
	private UserToGroupForm form;
	
	public UserToGroupPage(User user) {
		super();
		this.form = new UserToGroupForm("userToGroupForm", user);
		this.add(this.form);
		this.createList(user);
	}
	
	@SuppressWarnings("serial")
	public void createList(User user){
		add(new PropertyListView("list", this.getGroupsFromUser(user)) {
		    protected void populateItem(ListItem item) {
		        item.add(new Label("name"));
		    }
		});
	}
	
	protected List<Group> getGroupsFromUser(User user){
		List<Group> list;
		Session sess = HibernateUtil.getSessionFactory().getCurrentSession();
		Transaction tx = null;
		try {
			tx = sess.beginTransaction();
			sess.refresh(user);
			list = new ArrayList<Group>(user.getGroups());
			tx.commit();
		} catch (RuntimeException e) {
			if (tx != null)
				tx.rollback();
			throw e;
		} finally{
			if(sess.isOpen()) sess.close();
		}
		return list;
	}
}
